/**
 */
package com.openvas.core.gas.until;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 有大小限制的队列，
 * 每增加一条最新的数据放到队列，会顶掉一条旧数据
 */
public class SizeLimitedQueue<T> extends ConcurrentLinkedQueue<T> {
	private static final long serialVersionUID = 1L;
	//尺寸
	 private int limit; 
	
	public SizeLimitedQueue() {
	}
	
	public SizeLimitedQueue(int size) {
		this.limit = size;
	}
	

	public boolean add(T e) {
		synchronized (this) {
			while(size() >= limit){
				poll();
			}
			return super.add(e);
		}
	}

	public List<T> reverse(){
		List<T> list = new ArrayList<T>();
		list.addAll(this);
		Collections.reverse(list);
		return list; 
	}
	
	public int getSize() {
		return limit;
	}

	public void setSize(int size) {
		this.limit = size;
	}
	
	
	
	
	
	public static void main(String[] args) {
		final SizeLimitedQueue<String> queue = new SizeLimitedQueue<String>(10);
		class TT implements Runnable{
			int i;
			public TT(int i) {
				this.i = i;
			}
			public void run() {
				queue.add("t"+i);
				System.out.println(queue);
			}
		}
		
		ScheduledExecutorService service = Executors.newScheduledThreadPool(20);
		for (int i = 0; i < 100; i++) {
			service.scheduleAtFixedRate(new TT(i),0, 1, TimeUnit.SECONDS);
		}
	}
}
